/**
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xume.raob.extensions.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.xume.raob.Configuration;
import org.xume.raob.util.StringUtils;

/**
 * @author Johan Siebens
 */
public class JpaExtension {

	private static String DEFAULT_PERSISTENCE_UNIT_NAME = "jpa.persistenceUnitName";

	private EntityManager defaultEntityManager;

	public Object persist(Object entity) {
		return doPersist(entity, getDefaultEntityManager());
	}

	public Object persist(Object entity, EntityManager entityManager) {
		return doPersist(entity, entityManager);
	}

	public Object persist(Object entity, EntityManagerFactory entityManagerFactory) {
		return doPersist(entity, entityManagerFactory.createEntityManager());
	}

	private Object doPersist(Object entity, EntityManager em) {
		EntityTransaction transaction = em.getTransaction();
		boolean error = false;
		try {
			transaction.begin();
			em.persist(entity);
			return entity;
		} catch (Exception e) {
			error = true;
			throw new JpaExtensionException("Failed to persist entity", e);
		} finally {
			if (!error) {
				transaction.commit();
			} else {
				transaction.rollback();
			}
		}
	}

	private EntityManager getDefaultEntityManager() {
		if (defaultEntityManager == null) {
			String persistenceUnitName = Configuration.getProperty(DEFAULT_PERSISTENCE_UNIT_NAME);
			if (StringUtils.isEmpty(persistenceUnitName)) {
				throw new JpaExtensionException("Required property [" + DEFAULT_PERSISTENCE_UNIT_NAME
						+ "] is missing in Raob configuration");
			}
			defaultEntityManager = Persistence.createEntityManagerFactory(persistenceUnitName).createEntityManager();
		}
		return defaultEntityManager;
	}

}
